package com.example.administrator.music;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.telephony.PhoneNumberUtils;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.bmob.sms.BmobSMS;
import cn.bmob.sms.listener.RequestSMSCodeListener;
import cn.bmob.sms.listener.VerifySMSCodeListener;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * Created by Administrator on 2018/3/30.
 */

public class ZhucheActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView back;
    private boolean xuanzhong=false;
    private EditText phone,yzm;
    private Button fasong,zhuche;
    private String yanzhenma;
    private EditText username,password;
    private String userne,passwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.zhuche);
        Bmob.initialize(this,"6aeb83da9239b94d7c6773a50f22c5d3");
        BmobSMS.initialize(this,"6aeb83da9239b94d7c6773a50f22c5d3");
        initview();
    }
    private void initview() {
        back= (ImageView) findViewById(R.id.zhanghaozhuche_back);
        phone= (EditText) findViewById(R.id.zhanghao_phone);
        fasong= (Button) findViewById(R.id.zhanghao_fasong);
        zhuche= (Button) findViewById(R.id.zhanghao_zhuche);
        yzm= (EditText) findViewById(R.id.zhanghao_yzm);
        username= (EditText) findViewById(R.id.username);
        password= (EditText) findViewById(R.id.password);

        fasong.setEnabled(false);
        zhuche.setEnabled(false);
        fasong.setOnClickListener(this);
        zhuche.setOnClickListener(this);
        fasong.setOnClickListener(this);
        back.setOnClickListener(this);

        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String phoneNo= String.valueOf(s);
                if(isPhoneNumber(phoneNo)){
                    fasong.setEnabled(true);
                    fasong.setBackgroundResource(R.drawable.button);
                }else {
                    fasong.setEnabled(false);
                    fasong.setBackgroundResource(R.drawable.huibutton);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        yzm.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String pgN= String.valueOf(phone.getText());
                String yanzM= String.valueOf(s);
                BmobSMS.verifySmsCode(ZhucheActivity.this, pgN, yanzM, new VerifySMSCodeListener() {
                    @Override
                    public void done(cn.bmob.sms.exception.BmobException e) {
                        if(e==null){
                            zhuche.setEnabled(true);
                            zhuche.setBackgroundResource(R.drawable.button);
                        }
                    }
                });
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.zhanghaozhuche_back:
                finish();
                break;
            case R.id.zhanghao_fasong:
                Toast.makeText(ZhucheActivity.this,"请稍候",Toast.LENGTH_SHORT).show();
                BmobQuery<MusicPlayUser> query=new BmobQuery<MusicPlayUser>();
                query.addWhereEqualTo("phongNo",String.valueOf(phone.getText()));
                query.findObjects(new FindListener<MusicPlayUser>() {
                    @Override
                    public void done(List<MusicPlayUser> list, BmobException e) {
                        if(list.size()==0){
                            String phongNo= String.valueOf(phone.getText());
                            BmobSMS.requestSMSCode(ZhucheActivity.this, phongNo, "Zzh短信验证服务", new RequestSMSCodeListener() {
                                @Override
                                public void done(Integer integer, cn.bmob.sms.exception.BmobException e) {
                                    if (e==null){
                                        Toast.makeText(ZhucheActivity.this,"验证码已发送，请注意查收",Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }else {
                            Toast.makeText(ZhucheActivity.this,"此号码已经注册了，请直接登录",Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }
                });

                break;
            case R.id.zhanghao_zhuche:
                  userne= String.valueOf(username.getText());
                  passwd= String.valueOf(password.getText());
                if(userne.equals("") || passwd.equals("") ){
                    Toast.makeText(ZhucheActivity.this,"用户名或密码不能为空",Toast.LENGTH_SHORT).show();
                }else {
                    File file1 = new File("/data/data/com.example.administrator.music/files/musicusername");
                    File file2 = new File("/data/data/com.example.administrator.music/files/musicuserobjectId");
                    if(file1.exists()){
                        file1.delete();
                    }
                    if(file2.exists()){
                        file2.delete();
                    }
                    MusicPlayUser musicPlayUser=new MusicPlayUser();
                    musicPlayUser.setUsername(userne);
                    musicPlayUser.setPassword(passwd);
                    musicPlayUser.setTheme(MainActivity.theme);
                    musicPlayUser.setPhongNo(String.valueOf(phone.getText()));
                    musicPlayUser.setMode(MainActivity.playmode);
                    musicPlayUser.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if(e==null){
                                LoginActivity.zhuc=true;
                                MenuActivity.zhuc=true;
                                saveMassage(userne,"musicusername");
                                saveMassage(s,"musicuserobjectId");
                                Toast.makeText(ZhucheActivity.this,"成功注册："+s,Toast.LENGTH_SHORT).show();
                                finish();
                            }else{
                                Toast.makeText(ZhucheActivity.this,"注册失败：" + e.getMessage(),Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
                break;
        }
    }
    public static boolean isPhoneNumber(String phoneNo) {
        if (TextUtils.isEmpty(phoneNo)) {
            return false;
        }
        if (phoneNo.length() == 11) {
            for (int i = 0; i < 11; i++) {
                if (!PhoneNumberUtils.isISODigit(phoneNo.charAt(i))) {
                    return false;
                }
            }
            Pattern p = Pattern.compile("^((13[^4,\\D])" + "|(134[^9,\\D])" +
                    "|(14[5,7])" +
                    "|(15[^4,\\D])" +
                    "|(17[3,6-8])" +
                    "|(18[0-9]))\\d{8}$");
            Matcher m = p.matcher(phoneNo);
            return m.matches();
        }
        return false;
    }
    Runnable runnable=new Runnable() {
        @Override
        public void run() {
            finish();
        }
    };


    public void saveMassage(String inputText,String textname) {//inputText为传入的要保存的数据
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try {
            //textname为文件名，第二个参数为文件操作模式：文件已经存在，就往文件里面追加类容，不从新创建文件。
            out = openFileOutput(textname, Context.MODE_APPEND);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(inputText);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
